package com.example.jchuah.tiles;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;


public class MyActivity extends Activity implements View.OnTouchListener, View.OnDragListener {

    int numRows = 5;
    int numCols = 4;

    View[][] grid = new View[numRows][numCols];
    GridLayout gridView;
    Random randGen = new Random();

    GestureDetector.SimpleOnGestureListener simpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (Math.abs(velocityX) > 1 || Math.abs(velocityY) > 1) {


                if (Math.abs(velocityX) > Math.abs(velocityY)) {

                    if (velocityX > 0) {

                        flingRight();

                    } else {

                        flingLeft();
                    }

                } else {

                    if (velocityY > 0) {

                        flingDown();

                    } else {

                        flingUp();
                    }
                }
            }

            return super.onFling(e1, e2, velocityX, velocityY);
        }
    };
    GestureDetector gestureDetector;

    View lastTouched = null;

    public void flingLeft() {
        Log.d("fling event", "left");
        RowColPair whereFrom =
                getRowColumn(lastTouched);
        View tileHold = new TextView(this);
        tileHold = extractTile(whereFrom);
        RowColPair whereTo = whereFrom.getLeft();
        View tileHold2 = new TextView(this);
        tileHold2 = extractTile(whereTo);
        addTile(whereTo, tileHold);
        addTile(whereFrom, tileHold2);


    }
    public void setLastTouched(View lastTouched) {
        this.lastTouched = lastTouched;
    }

    public View getLastTouched() {
        return lastTouched;
    }

    public View extractTile(RowColPair pair) {
        View tile = grid[pair.row][pair.col];
        grid[pair.row][pair.col] = null;
        gridView.removeView(tile);
        return tile;
    }

    public void example() {
        RowColPair whereFrom = getRowColumn(lastTouched);
        RowColPair whereToLeft = whereFrom.getLeft();

        if (isValidRowColPair(whereToLeft)) {
            View sourceTile = grid[whereFrom.row][whereFrom.col];
            View targetTile = grid[whereToLeft.row][whereToLeft.col];



            TextView sourceTileValue = (TextView)sourceTile.findViewById(R.id.value);
            String sourceTileValueText = (String)sourceTileValue.getText();
            TextView targetTileValue = (TextView)targetTile.findViewById(R.id.value);
            String targetTileValueText = (String)targetTileValue.getText();

            if (sourceTileValueText.equals(targetTileValueText)) {
            }
        }
    }


    public void addTile(RowColPair pair,View tile ) {
        addTile(pair.row, pair.col, tile);
    }

    public boolean isValidRowColPair(RowColPair pair) {
        return (pair.col >= 0 && pair.row >= 0 &&
                pair.row < grid.length && pair.col < grid[0].length);
    }

    public void flingRight() {
        Log.d("fling event", "right");
        RowColPair whereFrom =
                getRowColumn(lastTouched);
        View tileHold = new TextView(this);
        tileHold = extractTile(whereFrom);
        RowColPair whereTo = whereFrom.getRight();
        View tileHold2 = new TextView(this);
        tileHold2 = extractTile(whereTo);
        addTile(whereTo, tileHold);
        addTile(whereFrom, tileHold2);
    }

    public void flingUp() {
        Log.d("fling event", "up");
        RowColPair whereFrom =
                getRowColumn(lastTouched);
        View tileHold = new TextView(this);
        tileHold = extractTile(whereFrom);
        RowColPair whereTo = whereFrom.getAbove();
        View tileHold2 = new TextView(this);
        tileHold2 = extractTile(whereTo);
        addTile(whereTo, tileHold);
        addTile(whereFrom, tileHold2);
    }

    public void flingDown() {
        Log.d("fling event", "down");
        RowColPair whereFrom =
                getRowColumn(lastTouched);
        View tileHold = new TextView(this);
        tileHold = extractTile(whereFrom);
        RowColPair whereTo = whereFrom.getBelow();
        View tileHold2 = new TextView(this);
        tileHold2 = extractTile(whereTo);
        addTile(whereTo, tileHold);
        addTile(whereFrom, tileHold2);
    }

    public void generateGrid() {
        for (int row = 0; row < numRows; row++){
            for (int col = 0; col < numCols; col++) {
                View tile = getLayoutInflater()
                        .inflate(R.layout.tile, null);

                tile.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        TextView value = (TextView)view.findViewById(R.id.value);
                        RowColPair pair = getRowColumn(view);
                        Toast.makeText(MyActivity.this, "You touched " + value.getText() + " at row " + pair.row + " and column " + pair.col, Toast.LENGTH_LONG).show();

                        lastTouched = view;
                        return gestureDetector.onTouchEvent(motionEvent);
                    }
                });

                TextView value = (TextView)tile.findViewById(R.id.value);
                int randomInt = randGen.nextInt(2) + 1;
                int newNumber = (int)Math.pow(2, randomInt);
                value.setText(newNumber + "");

                addTile(row, col, tile);
            }
        }
    }

    public void OnStartNewPush(View view) {
        Intent intent = new Intent(this, MyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(intent);
    }

    public void addTile(int row, int col, View tile) {
        GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
        layoutParams.rowSpec = GridLayout.spec(row);
        layoutParams.columnSpec = GridLayout.spec(col);
        tile.setLayoutParams(layoutParams);

        gridView.addView(tile);
        grid[row][col] = tile;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        gridView = (GridLayout)findViewById(R.id.gridView);
        generateGrid();
        gestureDetector = new GestureDetector(this, simpleOnGestureListener);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onDrag(View view, DragEvent dragEvent) {
        return false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }

    public RowColPair getRowColumn(View view) {
        RowColPair result = new RowColPair();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == view) {
                    result.row = i;
                    result.col = j;
                    return result;
                }
            }
        }
        return result;
    }

    public View getTileAt(RowColPair pair) {
        return grid[pair.row][pair.col];
    }

    public boolean isEmpty(RowColPair pair) {
        return grid[pair.row][pair.col] == null;
    }

    class RowColPair {
        int row = -1;
        int col = -1;

        public Object clone() {
            RowColPair theClone = new RowColPair();
            theClone.row = row;
            theClone.col = col;
            return theClone;
        }

        public RowColPair getBelow() {
            RowColPair result = new RowColPair();
            result.row = row + 1;
            result.col = col;
            return result;
        }

        public RowColPair getAbove() {
            RowColPair result = new RowColPair();
            result.row = row - 1;
            result.col = col;
            return result;
        }
        public RowColPair getLeft() {
            RowColPair result = new RowColPair();
            result.row = row;
            result.col = col - 1;
            return result;
        }
        public RowColPair getRight() {
            RowColPair result = new RowColPair();
            result.row = row;
            result.col = col + 1;
            return result;}



        }


    }

